<?php

namespace Modules\Admin\Http\Controllers\Admin;

use App\Helpers\QueryBuilder;
use App\Http\Controllers\Admin\ApiController;
use App\Http\Resources\BaseResource;
use Modules\Admin\Entities\Permission;
use Modules\Admin\Http\Requests\PermissionRequest;
use Illuminate\Routing\Router;
use Modules\Admin\Services\PermissionService;

class PermissionController extends ApiController
{
    public function index(PermissionRequest $request)
    {
        $permissions = QueryBuilder::for(Permission::query())
            ->filters()
            ->fields()
            ->includes()
            ->sorts()
            ->orderBy('index', 'desc')
            ->get()
            ->toTree();
        $permissions = PermissionService::getInstance()->getMyPermissionsByTree($permissions->toArray(), $this->admin);
        return $this->success(BaseResource::collection($permissions));
    }

    /**
     * 说明：编辑权限【主要是将合适的权限设置为菜单】
     *
     * @return
     * @param   type
     * @author  daixinguo (daixinguo57@163.com)
     */
    public function update(Permission $permission, PermissionRequest $request)
    {
        $permission->update($request->only(['menu', 'page_name', 'hidden_menu', 'sort', 'icon']));
        return $this->success();
    }

    /**
     * 说明：通过获取所有路由刷新权限表【通过laravel-permission自带的方法进行添加这样可以沿用扩展的缓存机制】
     *
     * @return
     * @param   type
     * @author  daixinguo (daixinguo57@163.com)
     */
    public function refreshPermissionByRoute(Router $router)
    {
        $routes = PermissionService::getInstance()->refreshPermissionByRoute($router);
        return $this->success($routes);
    }
}
